package com.example.book.web;

import com.example.book.pojo.User;
import com.example.book.service.UserService;
import com.example.book.service.impl.UserServiceImpl;
import com.example.book.utils.WebUtils;
import com.google.gson.Gson;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import static com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY;

@WebServlet(name = "UserServlet", value = "/userServlet")
public class UserServlet extends BaseServlet {
    UserService userService = new UserServiceImpl();

    protected void ajaxExistsUsername(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取请求的参数
        String username = request.getParameter("username");
        //调用userService.existsUsername();
        boolean existsUsername = userService.existsUsername(username);
        //把返回的结果分装成为map对象
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("existsUsername", existsUsername);

        Gson gson = new Gson();
        String json = gson.toJson(resultMap);
        response.getWriter().write(json);
    }
        /**
         * 注销功能
         * @param request
         * @param response
         * @throws ServletException
         * @throws IOException
         */
    protected void logout(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.销毁session中用户登陆的信息(或者销毁session)
        request.getSession().invalidate();
        //2.重定向到首页(或者登陆页面)
        response.sendRedirect(request.getContextPath());
    }
    /**
     * 登陆功能
     * @param request
     * @param response
     */

    protected void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        //调用Service处理业务
        User login = userService.login(new User(null, username, password, null));


        if (login==null){
            //登陆失败
            //跳回登陆界面
            request.setAttribute("msg","用户名或密码错误");
            request.setAttribute("username",username);
            request.getRequestDispatcher("/pages/user/login.jsp").forward(request,response);
        }else {

            //登陆成功
            //保存用户登陆的信息到session域中
            request.getSession().setAttribute("user",login);
            //跳转到成功页面
            request.getRequestDispatcher("/pages/user/login_success.jsp").forward(request,response);
        }
    }

    /**
     * 注册功能
     * @param request
     * @param response
     */
    protected void regist(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取session中的验证码
        String token = (String) request.getSession().getAttribute(KAPTCHA_SESSION_KEY);
        //删除Session中的验证码
        request.getSession().removeAttribute(KAPTCHA_SESSION_KEY);


        //1.获取请求的参数
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String email = request.getParameter("email");
        String code = request.getParameter("code");





        User user =  WebUtils.copyParamToBean(request.getParameterMap(),new User());
        //2.检查 验证码是否正确 ===>写死 abcd

        if (token!=null&&token.equalsIgnoreCase(code)){
            //正确
            //3.检查 用户名是否可用
            if (userService.existsUsername(username)){
                //不可用
                request.setAttribute("username",username);
                request.setAttribute("email",email);
                request.setAttribute("msg","用户名["+username+"]已存在");
                System.out.println("用户名["+username+"]已存在");
                //跳回注册页面
                request.getRequestDispatcher("/pages/user/regist.jsp").forward(request,response);
            }else {
                //可用
                //调用service保存到数据库
                userService.regisUser(new User(null,username,password,email));
                //跳转到注册成功页面
                request.getRequestDispatcher("/pages/user/regist_success.jsp").forward(request,response);
            }


        }else {
            //不正确
            //跳回注册页面
            request.setAttribute("username",username);
            request.setAttribute("email",email);
            request.setAttribute("msg","验证码["+code+"]错误");
            System.out.println("验证码["+code+"]错误");
            request.getRequestDispatcher("/pages/user/regist.jsp").forward(request,response);
        }
    }

}
